package com.lifeverse.repository;

import com.lifeverse.entity.PatternAlert;
import com.lifeverse.entity.enums.AlertSeverity;
import com.lifeverse.entity.enums.AlertStatus;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 模式预警数据访问接口
 */
@Repository
public interface PatternAlertRepository extends JpaRepository<PatternAlert, Long> {

    /**
     * 根据生命体ID查找预警
     */
    List<PatternAlert> findByLifeEntityId(Long lifeEntityId);

    /**
     * 根据模式ID查找预警
     */
    List<PatternAlert> findByPatternId(Long patternId);

    /**
     * 根据状态查找预警
     */
    List<PatternAlert> findByStatus(AlertStatus status);

    /**
     * 根据严重程度查找预警
     */
    List<PatternAlert> findBySeverity(AlertSeverity severity);

    /**
     * 查找未解决的预警
     */
    @Query("SELECT pa FROM PatternAlert pa WHERE pa.status IN ('NEW', 'ACKNOWLEDGED', 'IN_PROGRESS') ORDER BY pa.severity DESC, pa.triggeredAt DESC")
    List<PatternAlert> findUnresolvedAlerts();

    /**
     * 查找高优先级预警
     */
    @Query("SELECT pa FROM PatternAlert pa WHERE pa.severity IN ('HIGH', 'CRITICAL') AND pa.status != 'RESOLVED' ORDER BY pa.triggeredAt DESC")
    List<PatternAlert> findHighPriorityAlerts();

    /**
     * 根据时间范围查找预警
     */
    @Query("SELECT pa FROM PatternAlert pa WHERE pa.triggeredAt >= :startTime AND pa.triggeredAt <= :endTime")
    List<PatternAlert> findByTimeRange(@Param("startTime") LocalDateTime startTime, 
                                      @Param("endTime") LocalDateTime endTime);

    /**
     * 分页查询生命体的预警
     */
    Page<PatternAlert> findByLifeEntityId(Long lifeEntityId, Pageable pageable);

    /**
     * 统计未解决预警数量
     */
    @Query("SELECT COUNT(pa) FROM PatternAlert pa WHERE pa.lifeEntityId = :lifeEntityId AND pa.status IN ('NEW', 'ACKNOWLEDGED', 'IN_PROGRESS')")
    Long countUnresolvedByLifeEntityId(@Param("lifeEntityId") Long lifeEntityId);

    /**
     * 查找需要关注的预警
     */
    @Query("SELECT pa FROM PatternAlert pa WHERE pa.alertScore >= :threshold AND pa.status != 'RESOLVED' ORDER BY pa.alertScore DESC")
    List<PatternAlert> findAlertsRequiringAttention(@Param("threshold") Double threshold);
}